﻿<template>
  <div></div>
</template>

<script>
import G6Editor from '@antv/g6-editor'
export default {
  data () {
    return {
      selectedModel: {}, // 当前选中项数据模型
      curZoom: 1, // 当前缩放比率
      minZoom: 0.5, // 最小缩放比率
      maxZoom: 2, // 最大缩放比率
      page: '',
      editor: null
    }
  },
  mounted () {
    this.initEditor()
  },
  methods: {
    // 初始化editor
    initEditor () {
      // 生成 G6 Editor 编辑器
      const height = window.innerHeight - 230
      this.editor = new G6Editor()
      const toolbar = new G6Editor.Toolbar({
        container: 'toolbar'
      })
      const contextmenu = new G6Editor.Contextmenu({
        container: 'contextmenu'
      })
      const itempannel = new G6Editor.Itempannel({
        container: 'itempannel'
      })
      const detailpannel = new G6Editor.Detailpannel({
        container: 'detailpannel'
      })
      this.page = new G6Editor.Flow({
        graph: {
          container: 'page',
          height
        },
        align: {
          grid: true
        }
      })
      this.page.on('afteritemunselected', ev => {
        this.selectedModel = ''
      })
      this.page.on('afteritemselected', ev => {
        this.selectedModel = ev.item.getModel()
      })
      this.page.on('afteredgeselected', ev => {
        this.selectedModel = ev.item.getModel()
      })
      this.page.on('afterzoom', ev => {
        this.curZoom = ev.updateMatrix[0]
      })
      // 输入锚点不可以连出边
      this.page.on('hoveranchor:beforeaddedge', ev => {
        if (ev.anchor.type === 'input') {
          ev.cancel = true
        }
      })
      this.page.on('dragedge:beforeshowanchor', ev => {
        // 只允许目标锚点是输入，源锚点是输出，才能连接
        if (!(ev.targetAnchor.type === 'input' && ev.sourceAnchor.type === 'output')) {
          ev.cancel = true
        }
        // 如果拖动的是目标方向，则取消显示目标节点中已被连过的锚点
        if (ev.dragEndPointType === 'target' && this.page.anchorHasBeenLinked(ev.target, ev.targetAnchor)) {
          ev.cancel = true
        }
        // 如果拖动的是源方向，则取消显示源节点中已被连过的锚点
        if (ev.dragEndPointType === 'source' && this.page.anchorHasBeenLinked(ev.source, ev.sourceAnchor)) {
          ev.cancel = true
        }
      })
      this.editor.add(toolbar)
      this.editor.add(contextmenu)
      this.editor.add(itempannel)
      this.editor.add(detailpannel)
      this.editor.add(this.page)
      this.page.changeAddEdgeModel({
        shape: 'flow-smooth',
        label: '',
        actioncode: '',
        extenddata: '',
        events: []
      })
      // 展示网格
      this.page.showGrid()
    },
    changeZoom (zoom) {
      this.page.zoom(zoom)
    },
    updateGraph (key, value) {
      this.editor.executeCommand(() => {
        const selectedItems = this.page.getSelected()
        selectedItems.forEach(item => {
          const updateModel = {}
          updateModel[key] = value
          this.page.update(item, updateModel)
        })
      })
    }
  }
}
</script>
